package com.wms.common.interceptor;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.wms.common.exception.CIException;


public class ExceptionInterceptor extends AbstractInterceptor{
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(ExceptionInterceptor.class);
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String result = "input";
		try {
			result = invocation.invoke();
		}catch(CIException e){
			this.dealWithException(invocation, e);
		}catch(Exception e){
			this.dealWithException(invocation, e);
		}
		return result;
	}


	/**
	 * Transfer the exception into action errors if the action extends ActionSupport class. 
	 * The front page will display this exception by use <s:actionErrors/> tag.
	 * If not, throw this exception directly. 
	 * The front page will catch and display it by use the other tag.
	 * @param invocation
	 * @param e
	 * @throws Exception
	 */
	private void dealWithException(ActionInvocation invocation , Exception e) throws Exception{
		Action action = (Action)invocation.getAction();
		ActionSupport actionSupport = (ActionSupport)action;
		String message = "";
		if(action instanceof ActionSupport){
			if(e instanceof CIException){
				CIException ce = (CIException)e;
				String code = ce.getErrorCode();
				List args = ce.getArgs();
				try{
					if(null!=args && 0!=args.size()){
						message = actionSupport.getText(code, args);
					}else{
						message = actionSupport.getText(code);
					}
				}catch(Exception ex){
					message = e.getMessage();
					String m = e.getCause().getMessage();
					message = (m != null)? m:e.getCause().toString();
				}
			}else{
				message = e.getMessage();
			}
			actionSupport.addActionError(message);
		}else{
			message = e.getMessage();
			if(message != null){
				actionSupport.addActionError(message);
			}else{
				throw e;
			}
		}
		logger.error(message, e);
		ArrayList errors = (ArrayList)actionSupport.getActionErrors();
		if(errors != null && errors.size() > 1){
			String firstError = (String)errors.get(0);
			String secondError = (String)errors.get(1);
			if(firstError != null && firstError.equals(secondError)){
				actionSupport.clearErrorsAndMessages();
				actionSupport.addActionError(firstError);
			}
		}
	}
}
